<template>
  <el-dialog
    v-model="dialogVisible"
    title="上传送货单"
    width="800"
    overflow
    @close="handleClose"
  >
    <el-form
      ref="ruleFormRef"
      :model="form"
      style="margin: 20px"
      label-width="100px"
      :rules="rules"
    >
      <el-form-item label="上传日期" style="width: 90%" label-width="120px">
        <el-date-picker
          v-model="form.supplyTime"
          type="date"
          placeholder="请选择 上传日期"
          style="width: 100%"
          value-format="YYYY-MM-DD"
          disabled
        />
      </el-form-item>
      <el-form-item label="上传说明" style="width: 90%" label-width="120px">
        <el-input
          v-model="form.supplyMark"
          autocomplete="off"
          placeholder="请输入 上传说明"
        />
      </el-form-item>
      <el-form-item label="云采发货附件" style="width: 90%" label-width="120px">
        <el-button color="#1E3485" @click="openViewForPurchaseyc()">
          预览下载</el-button
        >
      </el-form-item>
      <el-form-item
        label="云采附件"
        style="width: 90%"
        label-width="120px"
        prop="supplyConfirmFile"
      >
        <el-upload
          v-model:file-list="form.supplyConfirmFileList"
          class="upload-demo"
          :action="uploadUrl"
          :headers="headers"
          multiple
          :on-preview="handlePreview"
          :on-success="handleSuccess"
          :limit="3"
        >
          <el-button :icon="Upload" color="#1E3485"> 点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">(请下载云采发货单附件，盖章上传)</div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="厂家送货单附件"
        style="width: 90%"
        label-width="120px"
        prop="shipmentFiles"
      >
        <el-upload
          v-model:file-list="form.shipmentFilesList"
          class="upload-demo"
          :action="uploadUrl"
          :headers="headers"
          multiple
          :on-preview="handlePreview"
          :on-success="handleSuccess2"
          :limit="3"
        >
          <el-button :icon="Upload" color="#1E3485"> 点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip" />
          </template>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" color="#1E3485" @click="update(ruleFormRef)">
          保存
        </el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 弹窗组件 -->
  <div class="dialogs">
    <filePreview
      :visible="filePreviewVisible"
      :fileId="fileId"
      :fileType="fileType"
      @close="closeFilePreview"
    />
  </div>
</template>
<script setup lang="ts">
import { reactive, ref, watch, onMounted } from "vue";
import { headers, uploadUrl, getDictDetail } from "@/api/utils";
import type { UploadProps, UploadUserFile } from "element-plus";
import type {
  ComponentSize,
  FormInstance,
  FormRules,
  UploadFile
} from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Upload } from "@element-plus/icons-vue";

import { getposupplyupload } from "@/api/ERP_SupplyManage";

import filePreview from "@/components/filePreview.vue";
// 弹窗关闭/打开事件
const props = defineProps({
  visible: Boolean,
  id: String
});

const emit = defineEmits(["close", "confirm"]);
function handleClose() {
  emit("close", false);
}

const ruleFormRef = ref<FormInstance>();
const dialogVisible = ref(false);
//const formLabelWidth = "140px";

onMounted(() => {
  form.supplyTime = new Date().toISOString().slice(0, 10);
});

let form = reactive({
  id: "",
  supplyTime: "",
  supplyMark: "",
  supplyConfirmFile: "",
  shipmentFiles: "",
  supplyConfirmFileList: [],
  shipmentFilesList: []
});

const rules = reactive({
  supplyConfirmFile: [
    { required: true, message: "请上传云采附件", trigger: "blur" }
  ],
  shipmentFiles: [
    { required: true, message: "请上传厂家送货单附件", trigger: "blur" }
  ]
});

watch(
  () => props.visible,
  val => {
    dialogVisible.value = val;
    form.id = props.id;
    form.supplyMark = "";
    form.supplyConfirmFile = "";
    form.shipmentFiles = "";
    form.supplyConfirmFileList = [];
    form.shipmentFilesList = [];
  },
  { immediate: true }
);

//上传
const fileList = ref<UploadUserFile[]>([]);
const contractFileList: any = [];
const filePreviewDialogVisible = ref(false);
const fileUrl = ref("");

const handleRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile: UploadFile) => {
  if (uploadFile.response) {
    const response = uploadFile.response as unknown as any;
    window.open(response.data.url, "_blank");
  } else {
    window.open(uploadFile.url, "_blank");
  }
};

// 文件上传成功,传参赋值，格式修改
const handleSuccess = (fileList: any) => {
  contractFileList.push(fileList.data);
  const formatterObj = [];
  for (let i in contractFileList) {
    let tempvalue: any = {};
    tempvalue.fileUrl = contractFileList[i].url;
    tempvalue.fileSuffix =
      "." +
      contractFileList[i].name.substring(
        contractFileList[i].name.lastIndexOf(".") + 1
      );
    tempvalue.fileOriginName = contractFileList[i].name;
    formatterObj.push(tempvalue);
  }
  form.supplyConfirmFile = JSON.stringify(formatterObj);
};
const handleSuccess2 = (fileList: any) => {
  contractFileList.push(fileList.data);
  const formatterObj = [];
  for (let i in contractFileList) {
    let tempvalue: any = {};
    tempvalue.fileUrl = contractFileList[i].url;
    tempvalue.fileSuffix =
      "." +
      contractFileList[i].name.substring(
        contractFileList[i].name.lastIndexOf(".") + 1
      );
    tempvalue.fileOriginName = contractFileList[i].name;
    formatterObj.push(tempvalue);
  }
  form.shipmentFiles = JSON.stringify(formatterObj);
};

// 预览弹窗
let filePreviewVisible = ref(false);
let fileId = ref("");
let fileType = ref("");

// 云采表格预览
function openViewForPurchaseyc() {
  fileId.value = props.id as string;
  fileType.value = "supplyShippingOrder";
  filePreviewVisible.value = true;
}

function closeFilePreview(val: boolean) {
  filePreviewVisible.value = val;
}

const update = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      Update();
    } else {
      console.log("error submit!", fields);
    }
  });
};
const Update = async () => {
  let data: any = {};
  data.id = props.id;
  data.supplyTime = form.supplyTime;
  data.supplyMark = form.supplyMark;
  data.supplyConfirmFile = form.supplyConfirmFile;
  data.shipmentFiles = form.shipmentFiles;
  const all = await getposupplyupload(data).then((response: any) => {
    if (response.code == 200) {
      handleClose();
      ElMessage({
        message: "上传成功",
        type: "success"
      });
      //history.back();
    }
    console.log(response);
  });
};
</script>
